import Taro from '@tarojs/taro'
import { View, Image, Button, Input } from '@tarojs/components'
import { useEffect, useState } from 'react'
import styles from './index.module.scss'
import { getWxlogin } from '@/apis/login'

const RehabComplete = () => {
    useEffect(() => {
        Taro.hideHomeButton()
    }, [])

    const defaultAvatarUrl =
        'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

    const [avatarUrl, setAvatarUrl] = useState(defaultAvatarUrl)
    const [nickname, setNickname] = useState('')

    const handleClick = () => {
        if (avatarUrl === defaultAvatarUrl) {
            Taro.showToast({
                title: '请选择头像',
                icon: 'none',
                duration: 2000,
            })
            return
        }
        if (nickname.trim() === '') {
            Taro.showToast({
                title: '请输入昵称',
                icon: 'none',
                duration: 2000,
            })
            return
        }
        Taro.login({
            success: async function (res) {
                if (res.code) {
                    // 发起网络请求
                    const data = await getWxlogin(res.code, nickname)
                    Taro.setStorageSync(
                        'userInfo',
                        JSON.stringify({
                            avatarUrl,
                            nickname,
                            token: data.token,
                        })
                    )
                    Taro.switchTab({ url: '/pages/me/index' })
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            },
        })
    }

    return (
        <View className={styles.container}>
            <Button
                className={styles.avatarWrapper}
                onChooseAvatar={({ detail }) => setAvatarUrl(detail.avatarUrl)}
                open-type='chooseAvatar'
            >
                <Image className={styles.avatar} src={avatarUrl}></Image>
            </Button>

            <View className={styles.fromItem}>
                <View className={styles.fromItemLabel}>昵称</View>
                <View className={styles.fromItemFrom}>
                    <Input
                        value={nickname}
                        onInput={({ detail }) => setNickname(detail.value)}
                        type='nickname'
                        placeholder='请输入昵称'
                    />
                </View>
            </View>
            <View className={styles.buttonWrapper}>
                <View onClick={handleClick} className={styles.button}>
                    确定
                </View>
            </View>
        </View>
    )
}
export default RehabComplete
